package com.ruoyi.web.controller.ora;

import com.ruoyi.common.annotation.KeyValidate;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.dict.DevicePermission;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.ora.domain.Device;
import com.ruoyi.ora.domain.DeviceMigration;
import com.ruoyi.ora.domain.DevicePosition;
import com.ruoyi.ora.domain.DeviceUser;
import com.ruoyi.ora.service.IDeviceMigrationService;
import com.ruoyi.ora.service.IDevicePositionService;
import com.ruoyi.ora.service.IDeviceService;
import com.ruoyi.ora.service.IDeviceUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 设备Controller
 * 
 * @author liuwp
 * @date 2024-11-14
 */
@RestController
@RequestMapping("/ora/device")
public class DeviceController extends BaseController
{
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDevicePositionService devicePositionService;

    @Autowired
    private IDeviceUserService deviceUserService;
    @Autowired
    private IDeviceMigrationService deviceMigrationService;

    /**
     * 查询设备列表
     */
    @PreAuthorize("@ss.hasPermi('ora:device:list')")
    @GetMapping("/list")
    public TableDataInfo list(Device device)
    {
        startPage();
        List<Device> list = deviceService.selectDeviceList(device);
        return getDataTable(list);
    }

    /**
     * 导出设备列表
     */
    @PreAuthorize("@ss.hasPermi('ora:device:export')")
    @Log(title = "设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Device device)
    {
        List<Device> list = deviceService.selectDeviceList(device);
        ExcelUtil<Device> util = new ExcelUtil<Device>(Device.class);
        util.exportExcel(response, list, "设备数据");
    }

    /**
     * 获取设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('ora:device:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(deviceService.selectDeviceById(id));
    }

    /**
     * 新增设备
     */
    @PreAuthorize("@ss.hasPermi('ora:device:add')")
    @Log(title = "设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Device device)
    {
        return toAjax(deviceService.insertDevice(device));
    }

    /**
     * 修改设备
     */
    @PreAuthorize("@ss.hasPermi('ora:device:edit')")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Device device)
    {
        return toAjax(deviceService.updateDevice(device));
    }

    /**
     * 删除设备
     */
    @PreAuthorize("@ss.hasPermi('ora:device:remove')")
    @Log(title = "设备", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(deviceService.deleteDeviceByIds(ids));
    }


    @PreAuthorize("@ss.hasPermi('ora:device:bind')")
    @Log(title = "设备绑定", businessType = BusinessType.OTHER)
    @PostMapping("/bind")
    public AjaxResult bind(@RequestBody DeviceUser deviceUser)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        deviceUser.setUserId(user.getUserId());
        return deviceService.deviceBindHandle(deviceUser);
    }

    @PreAuthorize("@ss.hasPermi('ora:device:unbind')")
    @Log(title = "设备解绑", businessType = BusinessType.OTHER)
    @PostMapping("/unbind")
    public AjaxResult unbind(@RequestBody Device device)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        return deviceService.deviceUnbindHandle(device, user);
    }

    @PreAuthorize("@ss.hasPermi('ora:device:mine')")
    @Log(title = "我的设备", businessType = BusinessType.OTHER)
    @GetMapping("/mine")
    public AjaxResult mine(Device device)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        return deviceService.deviceMineList(device, user);
    }


    @Log(title = "设备迁移", businessType = BusinessType.UPDATE)
    @PostMapping("migration")
    public AjaxResult migration(@RequestBody DeviceMigration deviceMigration)
    {
        if (deviceMigration.getFromDeviceId() != null && deviceMigration.getToDeviceId() != null && deviceMigration.getMigrationType() != null){
            if (deviceMigration.getFromDeviceId().equals(deviceMigration.getToDeviceId())){
                return AjaxResult.error(MessageUtils.message("ora.device.migration.same"));
            }

            long userId = SecurityUtils.getUserId();
            // 临时使用哈
            deviceMigration.setUserId(userId);

            DeviceUser fromDeviceUser = deviceUserService.selectOneDeviceUser(Builder.of(DeviceUser::new).with(DeviceUser::setUserId, userId).with(DeviceUser::setDeviceId, deviceMigration.getFromDeviceId()).build());
            DeviceUser toDeviceUser = deviceUserService.selectOneDeviceUser(Builder.of(DeviceUser::new).with(DeviceUser::setUserId, userId).with(DeviceUser::setDeviceId, deviceMigration.getToDeviceId()).build());

            if (fromDeviceUser == null || toDeviceUser == null || (fromDeviceUser.getDevicePermission().intValue() != DevicePermission.ADMIN.getValue()) || toDeviceUser.getDevicePermission().intValue() != DevicePermission.ADMIN.getValue()){
                return AjaxResult.error(MessageUtils.message("ora.device.migration.admin"));
            }

            if (deviceMigration.getMigrationType() == 1){
                // 全部数据迁移
                deviceService.deviceFamilyCircleDataMigration(deviceMigration);
                deviceService.deviceVoiceDataMigration(deviceMigration);
            } else if (deviceMigration.getMigrationType() == 2) {
                // 家庭圈数据迁移
                deviceService.deviceFamilyCircleDataMigration(deviceMigration);
            } else if (deviceMigration.getMigrationType() == 3) {
                // 录音数据迁移
                deviceService.deviceVoiceDataMigration(deviceMigration);
            }

            deviceMigrationService.insertDeviceMigration(deviceMigration);
            return AjaxResult.success();
        }else {
            return AjaxResult.error(MessageUtils.message("ora.common.required"));
        }
    }


    @PostMapping("/report")
    @KeyValidate()
    public AjaxResult report(@RequestBody Device device)
    {
        if (StringUtils.isNotEmpty(device.getDeviceSn())){
            if (StringUtils.isNotEmpty(device.getDevicePosition())){
                device.setDevicePosition("POINT("+device.getDevicePosition().replace(",", " ")+")"); // 坐标是以 (longitude latitude)
            }

            Device device1 = deviceService.selectOneDevice(Builder.of(Device::new).with(Device::setDeviceSn, device.getDeviceSn()).build());
            if (device1 == null){
                device.setHeartTime(new Date());
                deviceService.insertDevice(device);

                devicePositionService.insertDevicePosition(Builder.of(DevicePosition::new).with(DevicePosition::setDeviceId, device.getId()).with(DevicePosition::setDevicePosition, device.getDevicePosition()).build());
                return AjaxResult.success(device);
            }else {
                device1.setDevicePosition(device.getDevicePosition());  // 坐标使用Point   然后坐标表也创建一条数据
                device1.setDeviceQuantity(device.getDeviceQuantity());
                device1.setDeviceVoltage(device.getDeviceVoltage());
                device1.setHeartTime(new Date());
                deviceService.updateDevice(device1);

                devicePositionService.insertDevicePosition(Builder.of(DevicePosition::new).with(DevicePosition::setDeviceId, device1.getId()).with(DevicePosition::setDevicePosition, device.getDevicePosition()).build());
                return AjaxResult.success(device1);
            }
        }else {
            return AjaxResult.error(MessageUtils.message("ora.common.required"));
        }


    }

    @Log(title = "设备", businessType = BusinessType.INSERT)
    @PostMapping("network")
    @KeyValidate()
    public AjaxResult network(@RequestBody Device device)
    {
        if (StringUtils.isNotEmpty(device.getDeviceSn()) && StringUtils.isNotEmpty(device.getIccid())){
            Device device1 = deviceService.selectOneDevice(Builder.of(Device::new).with(Device::setDeviceSn, device.getDeviceSn()).build());
            if (device1 == null){
                device.setDeviceIcciid(device.getIccid());
                deviceService.insertDevice(device);
                return AjaxResult.success(device);
            }else {
                device1.setDeviceIcciid(device.getIccid());  // TODO 修改设备ICCID
                deviceService.updateDevice(device1);
            }
            return AjaxResult.success(device1);
        }else {
            return AjaxResult.error(MessageUtils.message("ora.common.required"));
        }
    }


}
